﻿using mozhi.smarterp.BasicData.PaymentTerms.Repositories;
using mozhi.smarterp.BasicData.PaymentTerms.Services;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;

namespace mozhi.smarterp.BasicData.PaymentTerms
{
    public class PaymentTermAppService : BasicDataAppService , IPaymentTermAppService
    {
        public IPaymentTermRepository _repository { get; set; }

        public PaymentTermManager _manager { get; set; }

        public PaymentTermAppService(IPaymentTermRepository repository, PaymentTermManager manager)
        {
            _repository = repository;
            _manager = manager;
        }

        public async Task<PaymentTermDto> GetAsync(Guid id)
        {
            var paymentTerm = await _repository.GetAsync(id);

            return ObjectMapper.Map<PaymentTerm , PaymentTermDto>(paymentTerm);
        }

        public async Task<PaymentTermDto> CreateAsync(PaymentTermCreateDto input)
        {
            var paymentTerm = await _manager.GetAsync(null, input.Code, input.Name, input.Activated, input.BasisType, input.Days, input.Type);

            paymentTerm = await _repository.InsertAsync(paymentTerm);

            return ObjectMapper.Map<PaymentTerm, PaymentTermDto>(paymentTerm);
        }

        public async Task<PaymentTermDto> UpdateAsync(PaymentTermUpdateDto input)
        {
            var paymentTerm = await _manager.GetAsync(input.Id, input.Code, input.Name, input.Activated, input.BasisType, input.Days, input.Type);

            paymentTerm = await _repository.UpdateAsync(paymentTerm);

            return ObjectMapper.Map<PaymentTerm, PaymentTermDto>(paymentTerm);
        }

        public async Task<PagedResultDto<PaymentTermDto>> GetListAsync(PaymentTermPagedResultRequestDto filter)
        {
            var paymentTerms = await _repository.GetPagedListAsync(filter.keyword, filter.Activated, filter.Type, filter.SkipCount, filter.MaxResultCount, filter.Sorting);

            var count = await _repository.GetCountAsync(filter.keyword , null , null , filter.Activated , null , filter.Type);

            return new PagedResultDto<PaymentTermDto>()
            {
                Items = ObjectMapper.Map<List<PaymentTerm>, List<PaymentTermDto>>(paymentTerms),
                TotalCount = count
            };
        }

        public async Task DeleteAsync(Guid id)
        {
            await _repository.DeleteAsync(id);
        }
    }
}
